<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.open_address_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="longitudeAndLatitude">
        <el-tag v-if="row.longitudeAndLatitude !== ''" type="primary">
          {{ longitudeAndLatitudeAddress(row.longitudeAndLatitude) }}
        </el-tag>
        <el-tag v-else type="info">未设置</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="memberId">
        <el-tag v-if="row.memberName && row.memberName !== ''" type="primary">{{ row.memberName }}</el-tag>
        <el-tag v-else type="info">无</el-tag>
      </template>
      <template slot-scope="{type, disabled}" slot="baseAddressIdForm">
        <el-autocomplete v-model="addressName" style="width: 100%" :fetch-suggestions="queryAddressAsync"
                         placeholder="搜索公共地址" @select="handleAddressSelect" clearable></el-autocomplete>
      </template>
      <template slot-scope="{type, disabled}" slot="lunchTimeRangeForm">
        <el-form-item label="">
          <el-switch v-model="lunchTimeRangeUse"
                     active-text="启用时间范围"
                     inactive-text="禁用时间范围">
          </el-switch>
        </el-form-item>
        <el-time-picker
          is-range
          v-if="lunchTimeRangeUse"
          v-model="lunchTimeRange"
          :format="'HH:mm'"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围">
        </el-time-picker>
      </template>
      <template slot-scope="{row}"
                slot="baseAddressId">
        <el-tag v-if="row.addressText !== ''" type="primary">
          {{ `【${row.merchantName}】${row.addressText}` }}
        </el-tag>
        <el-tag v-else type="info">未设置</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isTakeSelf">
        <el-tag v-if="row.isTakeSelf === 1" type="primary">
          自取
        </el-tag>
        <el-tag v-else type="info">配送</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="distance">
        <el-tag type="primary">{{ row.distance }} km</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="lunchTimeRange">
        <el-tag v-if="row.lunchTimeRange && row.lunchTimeRange !== ''" type="primary">{{ row.lunchTimeRange.replace(',', ' ~ ') }}</el-tag>
        <el-tag v-else type="info">未配置</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, getSelectPublic} from "@/api/address/open_address";
import {mapGetters} from "vuex";
import {dateTimeFormat} from "@/util/date";

export default {
  name: "MemberAddress",
  props: {
    member: {
      type: Object,
      default: {}
    },
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        tip: false,
        border: true,
        labelWidth: 150,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: "公共地址",
            prop: "baseAddressId",
            width: 200,
            row: true,
            span: 24,
            formslot: true,
            slot: true,
            overHidden: true,
          },
          {
            label: "距离",
            prop: "distance",
            slot: true,
            row: true,
            span: 24,
            overHidden: true,
            display: false,
          },
          {
            label: "送达时间",
            prop: "lunchTimeRange",
            slot: true,
            formslot: true,
            overHidden: true,
            span: 12,
          },
          {
            label: "联系人",
            prop: "name",
            row: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入联系人",
              trigger: "blur"
            }]
          },
          {
            label: "联系电话",
            prop: "tel",
            row: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入联系电话",
              trigger: "blur"
            }]
          },
          {
            label: "是否自取",
            prop: "isTakeSelf",
            slot: true,
            display: false,
          },
          {
            label: "是否团餐",
            prop: "isGroup",
            row: true,
            span: 24,
            type: "select",
            dicData: [
              {
                label: "是",
                value: 1
              },
              {
                label: "否",
                value: 2
              }
            ],
            value: 2,
            rules: [{
              required: true,
              message: "请输入联系电话",
              trigger: "blur"
            }]
          },
          {
            label: "公司名称",
            prop: "companyName",
            row: true,
            span: 24,
          },
          {
            label: "门牌",
            prop: "otherInfo",
            row: true,
            span: 24,
          },
        ]
      },
      data: [],
      isPublicOptions: [
        {
          value: 1,
          label: '公共'
        }, {
          value: 2,
          label: '私有'
        }
      ],
      openAddressList: [],
      addressName: '',
      lunchTimeRange: '',
      lunchTimeRangeUse: false,
      dinnerTimeRange: '',
      dinnerTimeRangeUse: false,
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.open_address_add, false),
        viewBtn: false,
        delBtn: this.vaildData(this.permission.open_address_delete, false),
        editBtn: this.vaildData(this.permission.open_address_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    longitudeAndLatitudeAddress() {
      return (val) => {
        let result = ''
        if (typeof val === 'string') {
          val = JSON.parse(val)
        }
        try {
          result = val.addressComponent.city + val.addressComponent.district + val.addressComponent.township + val.addressComponent.street + val.addressComponent.streetNumber
        } catch (e) {
          console.log(e)
        }
        return result
      }
    },
  },
  methods: {
    handleAddressSelect(val) {
      this.$set(this.form, 'baseAddressId', val.id)
    },
    queryAddressAsync(queryString, cb) {
      const restaurants = this.openAddressList.map(item => {
        if (item.isTakeSelf === 1) {
          item.value = `【${item.merchantName}】${item.addressText}(自取)`
        } else {
          item.value = `【${item.merchantName}】${item.addressText}(距离: ${item.distance}千米)`
        }
        return item;
      });
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().includes(queryString.toLowerCase()));
      };
    },
    rowSave(row, done, loading) {
      row.memberId = this.member.id
      row.isPublic = 2
      if (row.longitudeAndLatitude) {
        row.longitudeAndLatitude = JSON.stringify(row.longitudeAndLatitude)
      }
      if (!this.lunchTimeRange || this.lunchTimeRange === '') {
        row.lunchTimeRange = ''
      } else {
        row.lunchTimeRange = `${dateTimeFormat(this.lunchTimeRange[0], 'hh:mm')},${dateTimeFormat(this.lunchTimeRange[1], 'hh:mm')}`
      }
      if (!this.dinnerTimeRange || this.dinnerTimeRange === '') {
        row.dinnerTimeRange = ''
      } else {
        row.dinnerTimeRange = `${dateTimeFormat(this.dinnerTimeRange[0], 'hh:mm')},${dateTimeFormat(this.dinnerTimeRange[1], 'hh:mm')}`
      }
      if (!this.lunchTimeRangeUse) {
        row.lunchTimeRange = ''
      }
      if (!this.dinnerTimeRangeUse) {
        row.dinnerTimeRange = ''
      }
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.memberId = this.member.id
      row.isPublic = 2
      if (row.longitudeAndLatitude) {
        row.longitudeAndLatitude = JSON.stringify(row.longitudeAndLatitude)
      }
      if (!this.lunchTimeRange || this.lunchTimeRange === '') {
        row.lunchTimeRange = ''
      } else {
        row.lunchTimeRange = `${dateTimeFormat(this.lunchTimeRange[0], 'hh:mm')},${dateTimeFormat(this.lunchTimeRange[1], 'hh:mm')}`
      }
      if (!this.dinnerTimeRange || this.dinnerTimeRange === '') {
        row.dinnerTimeRange = ''
      } else {
        row.dinnerTimeRange = `${dateTimeFormat(this.dinnerTimeRange[0], 'hh:mm')},${dateTimeFormat(this.dinnerTimeRange[1], 'hh:mm')}`
      }
      if (!this.lunchTimeRangeUse) {
        row.lunchTimeRange = ''
      }
      if (!this.dinnerTimeRangeUse) {
        row.dinnerTimeRange = ''
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.addressName = ''
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          try {
            this.form.longitudeAndLatitude = JSON.parse(this.form.longitudeAndLatitude)
          } catch (e) {
            console.log(e)
          }
          if (this.form.lunchTimeRange && this.form.lunchTimeRange !== '') {
            this.lunchTimeRange = this.form.lunchTimeRange.split(',').map(item => {
              const hour = item.split(':')[0]
              const min = item.split(':')[1]
              return new Date(2024, 9, 10, hour, min)
            })
          }
          if (this.form.dinnerTimeRange && this.form.dinnerTimeRange !== '') {
            this.dinnerTimeRange = this.form.dinnerTimeRange.split(',').map(item => {
              const hour = item.split(':')[0]
              const min = item.split(':')[1]
              return new Date(2024, 9, 10, hour, min)
            })
          }
          this.openAddressList.forEach((ele) => {
            if (ele.id.toString() === this.form.baseAddressId.toString()) {
              if (ele.isTakeSelf === 1) {
                this.addressName = `【${ele.merchantName}】${ele.addressText}(自取)`
              } else {
                this.addressName = `【${ele.merchantName}】${ele.addressText}(距离: ${ele.distance}千米)`
              }
            }
          })
          if (this.lunchTimeRange && this.lunchTimeRange !== '') {
            this.lunchTimeRangeUse = true
          }
          if (this.dinnerTimeRange && this.dinnerTimeRange !== '') {
            this.dinnerTimeRangeUse = true
          }
        });
      } else if (type === "add") {
        this.$set(this.form, 'tel', this.member.phone)
        this.$set(this.form, 'name', this.member.name)
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.memberId = this.member.id
      this.query.isPublic = 2
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      getSelectPublic().then(res => {
        this.openAddressList = res.data.data
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.success-row{
  background-color: #b4e59e !important;
  color: #000000;
}
</style>
